import { defineStore } from 'pinia'
// 移除实际API调用
// import userApi from '../api/user'

// Mock数据
const mockUsers = [
  { id: 1, name: '张三', email: 'zhangsan@example.com', avatar: 'https://randomuser.me/api/portraits/men/1.jpg' },
  { id: 2, name: '李四', email: 'lisi@example.com', avatar: 'https://randomuser.me/api/portraits/women/2.jpg' },
  { id: 3, name: '王五', email: 'wangwu@example.com', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
  { id: 4, name: '赵六', email: 'zhaoliu@example.com', avatar: 'https://randomuser.me/api/portraits/women/4.jpg' },
  { id: 5, name: '钱七', email: 'qianqi@example.com', avatar: 'https://randomuser.me/api/portraits/men/5.jpg' },
  { id: 6, name: '孙八', email: 'sunba@example.com', avatar: 'https://randomuser.me/api/portraits/women/6.jpg' },
  { id: 7, name: '周九', email: 'zhoujiu@example.com', avatar: 'https://randomuser.me/api/portraits/men/7.jpg' },
  { id: 8, name: '吴十', email: 'wushi@example.com', avatar: 'https://randomuser.me/api/portraits/women/8.jpg' }
]

// Mock API服务
const mockUserApi = {
  // 获取用户列表
  getUsers({ page = 1, per_page = 6 } = {}) {
    const start = (page - 1) * per_page
    const end = start + per_page
    const paginatedUsers = mockUsers.slice(start, end)
    
    // 模拟API响应格式
    return Promise.resolve({
      data: paginatedUsers,
      total: mockUsers.length,
      page,
      per_page
    })
  },
  
  // 获取单个用户
  getUser(userId) {
    const user = mockUsers.find(u => u.id === userId)
    
    if (!user) {
      return Promise.reject(new Error('用户不存在'))
    }
    
    return Promise.resolve({ data: user })
  },
  
  // 创建用户
  createUser(userData) {
    // 生成新ID
    const newId = Math.max(...mockUsers.map(u => u.id)) + 1
    const newUser = { id: newId, ...userData }
    
    // 添加到mock数据中
    mockUsers.push(newUser)
    
    return Promise.resolve(newUser)
  },
  
  // 更新用户
  updateUser(userId, userData) {
    const index = mockUsers.findIndex(u => u.id === userId)
    
    if (index === -1) {
      return Promise.reject(new Error('用户不存在'))
    }
    
    // 更新用户数据
    const updatedUser = { ...mockUsers[index], ...userData }
    mockUsers[index] = updatedUser
    
    return Promise.resolve(updatedUser)
  },
  
  // 删除用户
  deleteUser(userId) {
    const index = mockUsers.findIndex(u => u.id === userId)
    
    if (index === -1) {
      return Promise.reject(new Error('用户不存在'))
    }
    
    // 从数组中删除
    mockUsers.splice(index, 1)
    
    return Promise.resolve({ success: true })
  }
}

// 定义一个使用封装API的用户管理store
export const useUserStore = defineStore('users-axios', {
  state: () => ({
    // 用户列表
    users: [],
    // 加载状态
    loading: false,
    // 错误信息
    error: null,
    // 当前选中的用户
    currentUser: null,
    // 分页信息
    pagination: {
      page: 1,
      perPage: 6,
      total: 0
    }
  }),
  
  getters: {
    // 获取用户总数
    totalUsers(state) {
      return state.users.length
    },
    
    // 获取是否有选中的用户
    hasSelectedUser(state) {
      return state.currentUser !== null
    }
  },
  
  actions: {
    // 获取用户列表
    async fetchUsers() {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockUserApi.getUsers({
          page: this.pagination.page,
          per_page: this.pagination.perPage
        })
        this.users = response.data
        this.pagination.total = response.total
        return response
      } catch (error) {
        this.error = error.message || '获取用户列表失败'
        console.error('获取用户列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取单个用户详情
    async fetchUserById(userId) {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockUserApi.getUser(userId)
        this.currentUser = response.data
        return response.data
      } catch (error) {
        this.error = error.message || '获取用户详情失败'
        console.error('获取用户详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 创建新用户
    async createUser(userData) {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockUserApi.createUser(userData)
        // 将新用户添加到列表中
        this.users.push(response)
        return response
      } catch (error) {
        this.error = error.message || '创建用户失败'
        console.error('创建用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 更新用户信息
    async updateUser(userId, userData) {
      this.loading = true
      this.error = null
      
      try {
        const response = await mockUserApi.updateUser(userId, userData)
        
        // 更新用户列表中的用户信息
        const index = this.users.findIndex(user => user.id === userId)
        if (index !== -1) {
          this.users[index] = { ...this.users[index], ...response }
        }
        
        // 如果当前选中的用户就是被更新的用户，也更新currentUser
        if (this.currentUser && this.currentUser.id === userId) {
          this.currentUser = { ...this.currentUser, ...response }
        }
        
        return response
      } catch (error) {
        this.error = error.message || '更新用户失败'
        console.error('更新用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 删除用户
    async deleteUser(userId) {
      this.loading = true
      this.error = null
      
      try {
        await userApi.deleteUser(userId)
        
        // 从用户列表中移除该用户
        this.users = this.users.filter(user => user.id !== userId)
        
        // 如果当前选中的用户就是被删除的用户，清空currentUser
        if (this.currentUser && this.currentUser.id === userId) {
          this.currentUser = null
        }
        
        return { success: true }
      } catch (error) {
        this.error = error.message || '删除用户失败'
        console.error('删除用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 设置当前页码
    setPage(page) {
      this.pagination.page = page
      // 获取新页码的数据
      return this.fetchUsers()
    },
    
    // 清空当前选中的用户
    clearCurrentUser() {
      this.currentUser = null
    },
    
    // 重置store状态
    resetState() {
      this.users = []
      this.loading = false
      this.error = null
      this.currentUser = null
      this.pagination.page = 1
    }
  }
})
